# 重写Django的authenticate 支持手机号验证查询
import re

from django.contrib.auth.backends import ModelBackend
from apps.users.models import User


class AuthModel(ModelBackend):
    # 重写用户验证方法
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 第一思路判断是前台还是后台登录，可以通过请求路径判断  /login/ 说明是前台的登录请求  /meiduo_admin/authorizations 后台的请求路径 request.path ==
        if request is None:
            # 后台登录 后台登录时调用authenticate方法未传递request
            # 判断用户是否是管理员 is_staff=True 说明是管理员
            try:
                user = User.objects.get(username=username, is_staff=True)
            except:
                user = None
            if user is not None and user.check_password(password):
                return user
        else:
            # 前台登录
            try:
                # 1、判断username是否是手机号
                if re.match(r'1[3-9]\d{9}', username):
                    # 按照手机号字段查询
                    user = User.objects.get(mobile=username)
                else:
                    # 按照用户名字段查询
                    user = User.objects.get(username=username)
            except:
                user = None

            if user is not None and user.check_password(password):
                # 校验密码
                return user
            return None
